package com.wing.sell.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.service.ProductDetailService;
import com.wing.sell.model.entity.Order;
import com.wing.sell.model.entity.OrderOfferDetail;
import com.wing.sell.model.entity.OrderPro;
import com.wing.sell.model.response.OrderProVO;
import com.wing.sell.service.OrderOfferDetailService;
import com.wing.sell.service.OrderProService;
import com.wing.sell.service.OrderService;
import com.wing.user.feign.UserClient;
import com.wing.user.model.response.UserVO;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.sell.model.entity.OrderOffer;
import com.wing.sell.model.request.OrderOfferForm;
import com.wing.sell.service.OrderOfferService;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author
 */
@Validated
@Api(value = "Admin-销售订单产品报价记录表管理", tags = "#/sell/orderOffer")
@RestController("orderOfferController")
@RequestMapping("sell/admin/orderOffer")
@RequiredArgsConstructor
@Slf4j
public class OrderOfferController {

    private final OrderOfferService orderOfferService;
    private final OrderOfferDetailService orderOfferDetailService;
    private final ProductDetailService productDetailService;
    private final OrderProService orderProService;
    private final OrderService orderService;
    private final UserClient userClient;

    @ApiOperation(value = "查询所有销售订单产品报价记录表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "sort", value = "排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "order", value = "排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<OrderOffer> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "desc") String order
            , Long orderId
    ) {

        Page<OrderOffer> pg = new Page<>(page, limit);
        QueryWrapper<OrderOffer> queryWrapper = new QueryWrapper<>();


        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }
        if (orderId != null) {
            queryWrapper.eq("order_id", orderId);
        }

        //查询所有的物料

        IPage<OrderOffer> list = orderOfferService.getBaseMapper().selectPage(pg, queryWrapper);

        List<OrderOfferDetail> orderOfferDetails = orderOfferDetailService.list();


        for (OrderOffer record : list.getRecords()) {
            record.setOrderOfferDetailList(orderOfferDetails.stream()
                    .filter(t -> Objects.equals(t.getOrderId(), record.getOrderId())
                            && t.getOfferId().equals(record.getId())).collect(Collectors.toList()));

            List<OrderOfferDetail> orderOfferDetailList = record.getOrderOfferDetailList();
            List<Long> collect = orderOfferDetailList.stream()
                    .map(OrderOfferDetail::getProductDetailId)
                    .filter(productDetailId -> ObjectUtil.isNotNull(productDetailId)).collect(Collectors.toList());
            Map<String,Object> map = new HashMap<>();
            map.put("ids",collect);
            List<ProductDetail> details = productDetailService.list4app(map);

            orderOfferDetailList.forEach(info -> {
                details.forEach(aa -> {
                    if (aa.getId().equals(info.getProductDetailId())) {
                        info.setSkuCode(aa.getSkuCode());
                    }
                });
            });
        }

        list.getRecords().forEach(z -> {
            UserVO userVO = userClient.getUserInfoByUserId(z.getCreator()).getData();
            if (ObjectUtil.isNotNull(userVO)) {
                z.setRoleName(userVO.getRoleName());
                z.setDeptName(userVO.getDepartmentName());
            }
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    @ApiOperation(value = "添加销售订单产品报价记录表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(OrderOfferForm.Add.class) @RequestBody OrderOfferForm orderOfferForm) {
        try {
            orderOfferService.add(orderOfferForm);
            return JsonResult.success("添加成功");
        } catch (Exception e) {
            log.error("添加失败:", e);
            return JsonResult.fail("添加失败" + e.getMessage());
        }
    }


    @ApiOperation(value = "修改销售订单产品报价记录表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(OrderOfferForm.Update.class) @RequestBody OrderOfferForm orderOfferForm) {//修改报价单 修改报价
        OrderOffer orderOffer = orderOfferService.getById(orderOfferForm.getId());
        if (orderOffer == null) {
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(OrderOffer.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(orderOfferForm, orderOffer, copyOptions);
        BigDecimal totalMoney = new BigDecimal(0);
        for (OrderOfferDetail orderOfferDetail : orderOffer.getOrderOfferDetailList()) {
            orderOfferDetail.setLastMoney(orderOfferDetail.getOfferMoney());
            orderOfferDetailService.updateById(orderOfferDetail);
            OrderProVO orderProVO = orderProService.get4appById(orderOfferDetail.getProId());
            totalMoney = totalMoney.add(orderOfferDetail.getOfferMoney().multiply(new BigDecimal(orderProVO.getQuantity())));//报价单总金额
        }
        orderOffer.setTotalMoney(totalMoney);

        LocalDateTime currentTime = orderOffer.getCreateTime();
        LocalDateTime offWorkTime = LocalDateTime.now();
        LocalDateTime tempDateTime = LocalDateTime.from(currentTime);
        long days = tempDateTime.until(offWorkTime, ChronoUnit.DAYS);
        tempDateTime = tempDateTime.plusDays(days);
        long hours = tempDateTime.until(offWorkTime, ChronoUnit.HOURS);
        tempDateTime = tempDateTime.plusHours(hours);
        long minutes = tempDateTime.until(offWorkTime, ChronoUnit.MINUTES);
        tempDateTime = tempDateTime.plusMinutes(minutes);
        long seconds = tempDateTime.until(offWorkTime, ChronoUnit.SECONDS);
        orderOffer.setUpdateDuring("" + days + " 天 " + hours + " 小时 " + minutes + " 分 " + seconds + " 秒");//更新时长

        if (orderOfferService.updateById(orderOffer)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    //报价单设为终版
    @ApiOperation(value = "报价单设为终版", notes = "修改")
    @PostMapping("/finalEdition")
    public JsonResult finalEdition(@RequestParam("id") Long id) {
        OrderOffer orderOffer = orderOfferService.getById(id);

        UpdateWrapper<OrderOffer> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("order_id", orderOffer.getOrderId()); // 根据 id 进行更新
        updateWrapper.set("whether_final", false); // 更新 name 字段
        orderOfferService.update(updateWrapper);

        orderOffer.setWhetherFinal(true);
        //设置单个为终极版本
        if (orderOfferService.updateById(orderOffer)) {
            //设置其他的
            //设为终版的报价单包含的产品的报价状态设为已报价
            List<OrderOfferDetail> orderOfferDetails = orderOfferDetailService.list(new QueryWrapper<OrderOfferDetail>().eq("offer_id", id));
            for (OrderOfferDetail orderOfferDetail : orderOfferDetails) {
                //设置订单未结束
                OrderPro orderPro = orderProService.getById(orderOfferDetail.getProId());
                orderPro.setOfferStatus(OrderPro.OfferStatus.finish);
                orderProService.updateById(orderPro);
            }
            //设为报价终版后，检查此订单下的所有报价单 是否都为有终版 全是则修改订单的状态，计算总金额
            QueryWrapper<OrderOffer> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id", orderOffer.getOrderId());
            queryWrapper.eq("whether_final", true);
            List<OrderOffer> list = orderOfferService.list(queryWrapper);
            BigDecimal amount = new BigDecimal(0);
            for (int i = 0; i < list.size(); i++) {
                amount = amount.add(list.get(i).getTotalMoney());
            }

            Order order = new Order();
            Order byId = orderService.getById(orderOffer.getOrderId());
            if (byId.getOrderRoot() == Order.OrderRoot.enquiry) {
                //订单下的所有报价单都为终版了,询价订单到待签约状态，直接添加的正式订单不改
                if (byId.getContractId()!=null) {
                    order.setStatus(Order.Status.signed);
                }else{
                    order.setStatus(Order.Status.tosign);
                }
            }
            order.setId(orderOffer.getOrderId());
            //订单总金额
            order.setAmount(amount);
            orderService.updateById(order);
            return JsonResult.success("修改成功");
        }
        return JsonResult.fail("修改失败");
    }


    @ApiOperation(value = "删除销售订单产品报价记录表", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderOfferId", value = "销售订单产品报价记录表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long orderOfferId) {
        if (orderOfferService.removeById(orderOfferId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    /**
     * 转为正式订单
     * @param id
     * @return
     */
    @ApiOperation(value = "转为正式订单", notes = "转为-正式订单")
    @PostMapping("/toZSOrder")
    public JsonResult toZSOrder(@RequestParam("id") Long id) {
        Order byId = orderService.getById(id);

        if (!byId.getStatus().equals(Order.Status.signed) && !byId.getStatus().equals(Order.Status.tosign)){
            return JsonResult.fail("当前状态不能转正式订单！");
        }
        byId.setUpdateTime(LocalDateTime.now());

        byId.setModifierName(JwtUtils.getLoginUsername());
        byId.setOrderType(Order.OrderType.mass);
        byId.setStatus(Order.Status.finish);
        boolean b = orderService.updateById(byId);
        if (b){
            return JsonResult.success("操作成功！");
        }
        return JsonResult.fail("操作失败！");
    }
}
